from flask import render_template,abort
from flask import Flask, Response, jsonify,request
from config import config
import saver
import os


class JsonResponse(Response):
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (list, dict,tuple)):
            response = jsonify(response)
        # return super().force_type(response, environ)
        return super(Response, cls).force_type(response, environ)

class JsonFlask(Flask):
    response_class = JsonResponse

def ok(data=None , status=0):
    return {'Status':status , "Data":data}

# app = Flask(__name__)
app = JsonFlask(__name__)

@app.route('/')
def hello_world():
    return config.get('fs' ,'root_dir')

@app.route('/test/upload')
def hello():
    return render_template('upload.html')

@app.route('/json')
def json():
	return [1,2,3,(123,21) ]

@app.route('/upload/<cat>', methods=['POST'])
def upload_file(cat):
    if 'file' not in request.files:
        return ok("file is empty" , 100)
    f = request.files['file']
    print(dir(f))
    cats = config.get('fs' , 'categories').split(',')
    if cat not in cats :
        return ok("category not ok" , 100)
    root_dir = config.get('fs','root_dir')
    rel_path = '/'+cat ,os.path.splitext(f.filename)[1]
    fullpath = saver.gen_path(root_dir+rel_path)
    saver.ensure_dirs(fullpath)
    f.save(fullpath)
    return ok(rel_path)

if __name__ == '__main__':
    app.run(port=9002)